package com.jzoom.zoom.admin.models;

import com.jzoom.zoom.common.annotations.Inject;
import com.jzoom.zoom.common.codec.HashStr;
import com.jzoom.zoom.common.utils.DatetimeUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

public class UploadService {
    @Inject
    private ConfigService configService;

    public String doUpload(String ext, FileItem file) throws IOException {
        String uploadDir = configService.getConfig("upload_dir");
        String uploadFormat = configService.getConfig("upload_format");
        return doUpload(uploadDir, uploadFormat, ext, file);
    }

    public String doUpload(String uploadDir, String uploadFormat, String ext, FileItem file) throws IOException {
        String name = HashStr.md5(UUID.randomUUID().toString()) + ext;
        String date = DatetimeUtils.date();
        File dir = new File(uploadDir, date);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        FileUtils.copyInputStreamToFile(file.getInputStream(),
                new File(dir,
                        name
                ));
        return String.format(uploadFormat,date,name);
    }
}
